package v1

import (
	"supervideo/app/models/video"
	"supervideo/app/requests"
	"supervideo/pkg/response"

	"github.com/gin-gonic/gin"
)

type VideoController struct {
	BaseAdminController
}

func (vc *VideoController) Index(c *gin.Context) {
	request := requests.PaginationRequest{}

	if ok := requests.Validate(c, &request, requests.Pagination); !ok {
		return
	}

	data, pager := video.Paginate(c, 10)
	response.JSON(c, gin.H{
		"data":  data,
		"pager": pager,
	})
}

func (zc *VideoController) Store(c *gin.Context) {
	request := requests.VideoRequest{}
	if ok := requests.Validate(c, &request, requests.VideoStore); !ok {
		return
	}

	videoModel := video.Video{
		Title:       request.Title,
		Sort:        request.Sort,
		Status:      request.Status,
		ZoneId:      request.ZoneId,
		DoubanUrl:   request.DoubanUrl,
		Grade:       float32(request.Grade),
		AsName:      request.Asname,
		Description: request.Description,
	}

	videoModel.Create()
	if videoModel.ID > 0 {
		response.Created(c, videoModel)
	} else {
		response.Abort500(c, "创建失败, 请稍后重试~")
	}
}

func (zc *VideoController) Update(c *gin.Context) {
	videoModel := video.Get(c.Param("id"))
	if videoModel.ID == 0 {
		response.Abort404(c)
		return
	}

	request := requests.VideoRequest{}
	if ok := requests.Validate(c, &request, requests.VideoStore); !ok {
		return
	}

	videoModel.Title = request.Title
	videoModel.Sort = request.Sort
	videoModel.Status = request.Status
	videoModel.ZoneId = request.ZoneId
	videoModel.DoubanUrl = request.DoubanUrl
	videoModel.Grade = float32(request.Grade)
	videoModel.AsName = request.Asname
	videoModel.Description = request.Description

	rowAffected := videoModel.Save()
	if rowAffected > 0 {
		response.Data(c, videoModel)
	} else {
		response.Abort500(c, "更新失败, 请稍后尝试~")
	}

}

func (zc *VideoController) Delete(c *gin.Context) {
	videoModel := video.Get(c.Param("id"))
	if videoModel.ID == 0 {
		response.Abort404(c)
		return
	}

	rowAffected := videoModel.Delete()
	if rowAffected > 0 {
		response.Success(c)
		return
	}

	response.Abort500(c, "删除失败,请稍后尝试~")

}

func (zc *VideoController) Show(c *gin.Context) {
	videoModel := video.Get(c.Param("id"))
	if videoModel.ID == 0 {
		response.Abort404(c)
		return
	}
	response.Data(c, videoModel)
}
